package com.itheima.servlet;

import com.itheima.domain.Emp;
import com.itheima.service.EmpService;
import com.itheima.service.impl.EmpServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/EmpServlet")
public class EmpServlet extends HttpServlet {

    private EmpService empService = new EmpServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String operation = request.getParameter("operation");
        if ("add".equals(operation)) {
            add(request,response);
        }else if ("findAll".equals(operation)){
                findAll(request,response);
        }

    }

    private void findAll(HttpServletRequest request, HttpServletResponse response) throws SecurityException, IOException, ServletException {
        List<Emp> list = empService.findAll();
        request.setAttribute("list",list);
        request.getRequestDispatcher("/list.jsp").forward(request,response);
    }

    private void add(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException  {
        // 获取所有的请求参数
        Map<String, String[]> map = request.getParameterMap();
        // 创建实体类存储请求参数
        Emp emp = new Emp();
        try {
            // 封装请求参数到emp对象
            BeanUtils.populate(emp,map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 调用service完成添加操作
        empService.add(emp);

        // 重定向到查询操作 （防止表单的重复提交）
        response.sendRedirect(request.getContextPath() + "/EmpServlet?operation=findAll");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
